<?php
namespace Upload\Controller;

use Think\Controller;
use Think\Upload;

/**
 * 文件上传工具
 * Create by Zhb
 * Create Date:2018-03-28 13:20:04
 */
class UploadController extends Controller
{


    public function uploadSingleFile()
    {

        $singleUpload = new Upload();
        //$singleUpload->rootPath = '.'.$singleUpload->rootPath;
        $singleUpload->saveName = 'com_create_guid';
//        $singleUpload->exts = C("IMAGE_SETTING");
        // var_dump($singleUpload);
        $fileInfo = $singleUpload->uploadOne();
        if (!$fileInfo) {

            \Common\Common\print_json_data(200, $fileInfo, $singleUpload->getError());

        } else {

            \Common\Common\print_json_data(200, $fileInfo, $singleUpload->getError());

        }
        exit;
    }


    public function uploadMultiFile()
    {

        $singleUpload = new Upload();
        //$singleUpload->rootPath = '.'.$singleUpload->rootPath;
        $singleUpload->saveName = 'com_create_guid';
        $singleUpload->exts = C("IMAGE_SETTING");
        // var_dump($singleUpload);
        $fileInfo = $singleUpload->upload();
        if (!$fileInfo) {

            \Common\Common\print_json_data(200, $fileInfo, $singleUpload->getError());

        } else {

            \Common\Common\print_json_data(200, $fileInfo, $singleUpload->getError());

        }
        exit;
    }

    public function uploadImageFile()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Uploads/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        // 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
//            $this->error($upload->getError());
            \Common\Common\print_json_data(201, $info, '图片上传出错');
        } else {// 上传成功
            $file_info = $info['file'];
            $save_path = './Uploads/' . $file_info['savepath'] . $file_info['savename'];
            $save_attachment = '/' . $file_info['savepath'] . $file_info['savename'];

            $where['uid'] = session('uid');
            $where['filename'] = $file_info['name'];
            $where['attachment'] = $save_attachment;
            $where['media_id'] = 0;
            $where['type'] = 'image';
            $where['tag'] = $save_path;
            $where['model'] = '永久';
            $where['createtime'] = time();

            $result = M('wx_attachment')
                ->data($where)
                ->add();
            if (empty($result)) {
                \Common\Common\print_json_data(202, $info, '图片存储出错');
            } else {
                $data['url'] = $save_path;
                $data['a_id'] = $result;
                \Common\Common\print_json_data(200, $data, '图片上传成功');
            }
        }
    }
}